package com.xuchaotong.zk.init;

import com.xuchaotong.zk.utils.ZookeeperUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @author 311633
 * @version 1.0
 * @ClassName:
 * @Description:
 * @date 2018/2/1 10:45
 */
@Configuration
public class ZookeeperListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOG = LoggerFactory.getLogger(ZookeeperListener.class);
    private CuratorFramework client = ZookeeperUtils.getInstance().getClient();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        String path = "/ROOTPATH/pds/child";
        ZookeeperUtils.getInstance().setNodeCacheListener(path, false);
    }

    private void setTreeCacheListener(final String path) {
        try {
            TreeCache treeCache = new TreeCache(client, path);
            TreeCacheListener treeCacheListener = new TreeCacheListener() {
                @Override
                public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                    ChildData data = event.getData();
                    if (data != null) {
                        switch (event.getType()) {
                            case NODE_ADDED:
                                LOG.info("[TreeCache]节点增加, path={}, data={}", data.getPath(), data.getData());
                                break;
                            case NODE_UPDATED:
                                LOG.info("[TreeCache]节点更新, path={}, data={}", data.getPath(), data.getData());
                                break;
                            case NODE_REMOVED:
                                LOG.info("[TreeCache]节点删除, path={}, data={}", data.getPath(), data.getData());
                                break;
                            default:
                                break;
                        }
                    } else {
                        LOG.info("[TreeCache]节点数据为空, path={}", "null");
                    }
                }
            };
            treeCache.getListenable().addListener(treeCacheListener);
            treeCache.start();
        } catch (Exception e) {
            LOG.error("创建TreeCache监听失败, path={}", path);
        }

    }
}
